import React, {useEffect, useState} from "react"
import {Button, Divider, Form, message, Modal, PageHeader, Popconfirm, Popover, Select, Table, Tag, Upload} from "antd";
import {
  ArrowLeftOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
  UploadOutlined,
  VerticalAlignBottomOutlined
} from "@ant-design/icons";
import cs from "classnames";
import SearchAutoComplete from "libs/search-auto-complete"
import {useRequest} from '@umijs/hooks'
import {HOST, orderType, pageSetting} from "project-config"
import {formatResult, useTableCheck} from "../../shared/libs/hooks/table-hooks"
import {get} from "server"
import {del, putJSON, putParam} from "../../shared/server"

import {clearner} from "../../shared/libs/utils"
import highlight from "../../shared/libs/highlight";
import {downloadSync} from "../../shared/libs/download"
import "./index.less"
import brandColors from "./brandColors"

const {confirm} = Modal;

const {Option} = Select;

const amountRender = (v, cls) => v ?
  <span><span className={cls || 'money-green'}>￥</span><span className={'amount'}>{v}</span></span> : '--'

const priceWidth = [100, 100, 100, 100, 80]

const Product = (props) => {

  const [form] = Form.useForm();
  const [brandList, setBrandList] = useState([]);
  const [defaultBrand, setDefaultBrand] = useState("");

  useEffect(() => {
    get("/management/brand/list").then(response => {
      setBrandList(response || [])
      setDefaultBrand(response && response[0].id || "");
    })
  }, [])

  const onDelete = (id) => {
    del(`/management/product/${id}`).then((data) => {
      if (data) {
        message.success('项目删除成功')
        onSearch()
      }
    })
  }

  const enableProduct = (row) => {
    putJSON(`/management/product/toggle/${row.id}?activated=${!row.activated}`).then((data) => {
      if (data) {
        message.success(data.activated ? "上架成功" : "下架成功")
        onSearch()
      }
    })
  }

  const updateProduct = (id) => {
    props.history.push(`/app/product/editcopy/${id}`)
  }

  //获取数据
  const getPageData = ({
                         current, pageSize, sorter, filters, searchKey,
                       }) => {
    let activated;
    if (filters && filters.activated && filters.activated.length === 1) {
      activated = filters.activated[0];
    }
    let sortKey;
    let sortType;
    if (sorter && sorter.columnKey && sorter.order) {
      sortKey = sorter.columnKey;
      sortType = orderType[sorter.order];
    }
    return get(`/management/product/${pageSize}/${current}`, clearner({
      searchKey,
      sortType,
      sortKey,
      activated,
    }))
  }


  //表格选中
  const {rowSelection, items} = useTableCheck({})
  //
  const {tableProps, params, refresh, pagination} = useRequest(getPageData, {
      paginated: true,
      defaultPageSize: 10,
      formatResult,
    }
  )

  const onSearch = (searchKey) => {
    params[0].searchKey = searchKey
    refresh().finally()
  }

  const onDeleteBatch = () => {
    if (items != null) {
      del(`/management/product/batch/${items.join(',')}`).then(result => {
        if (result) {
          message.success(`成功删除 ${items.length} 条用户`)
          onSearch()
        }
      })
    }
  }

  const onEnabledBatch = () => {
    if (items != null) {
      putParam(`/management/product/batch/toggle/${items.join(',')}`, {activated: true}).then(result => {
        if (result) {
          message.success(`成功上架 ${items.length} 条项目`)
          onSearch()
        }
      })
    }
  }

  const onDisabledBatch = () => {
    if (items != null) {
      putParam(`/management/product/batch/toggle/${items.join(',')}`, {activated: false}).then(result => {
        if (result) {
          message.success(`成功下架 ${items.length} 条项目`)
          onSearch()
        }
      })
    }
  }

  const showConfirm = (handle) => {
    const batchMapping = {
      Delete: {
        key: "删除",
        func: onDeleteBatch
      },
      Enabled: {
        key: "上架",
        func: onEnabledBatch
      },
      Disabled: {
        key: "下架",
        func: onDisabledBatch
      },
    }
    confirm({
      title: `确认${batchMapping[handle].key}`,
      icon: <ExclamationCircleOutlined/>,
      content: `确认要${batchMapping[handle].key}以下${items.length}记录?`,
      onOk() {
        batchMapping[handle].func();
      },
      onCancel() {
      },
    });
  }

  const productColumns = [
    {
      title: "项目编号",
      dataIndex: "itemNo",
      key: "itemNo",
      render: (v) => highlight(v, params[0].searchKey)
    }, {
      title: '项目名',
      key: 'name',
      dataIndex: 'name',
      width: 230,
      render: (v, record) => {
        const content = <div>
          <p>说明：{record.description}</p>
          <p>备注：{record.remarks}</p>
        </div>
        return <div style={{display: "flex", alignItems: "center"}}>
          <Popover content={content} title="项目详细">
            <QuestionCircleOutlined style={{color: "#1890ff", marginRight: 5}}/>
          </Popover>
          {highlight(v, params[0].searchKey)}
        </div>
      }
    },{
      title: '分类',
      width: 100,
      key: 'category',
      dataIndex: 'category'
    }, {
      title: '简码',
      width: 120,
      key: 'briefCode',
      dataIndex: 'briefCode',
      render: (v) => <Tag className={'large'}>{highlight(v.toUpperCase(), params[0].searchKey)}</Tag>
    }, {
      title: '价格',
      key: 'brandName',
      dataIndex: 'brandName',
      width: priceWidth[4],
      render: (_, record) => {
        const brandItem = record.prices.filter(item => item.brandId === defaultBrand)
        const brand = brandItem && brandItem[0] && brandItem[0]
        return brand ?
          <span className={'table-brand'}><span style={{backgroundColor: brandColors[brand.brandId]}}/>{brand.brandName}</span> : undefined
      }
    },
    {
      title: '固定成本价',
      key: 'fixedCostPrice',
      dataIndex: 'fixedCostPrice',
      width: priceWidth[0],
      render: (_, record) => {
        const brandItem = record.prices.filter(item => item.brandId === defaultBrand)
        return amountRender(brandItem[0] && brandItem[0] && brandItem[0].fixedCostPrice)
      }
    }, {
      title: '可变成本价',
      key: 'volatileCostPrice',
      dataIndex: 'volatileCostPrice',
      width: priceWidth[1],
      render: (_, record) => {
        const brandItem = record.prices.filter(item => item.brandId === defaultBrand)
        return amountRender(brandItem[0] && brandItem[0] && brandItem[0].volatileCostPrice)
      }
    }, {
      title: '其他成本价',
      key: 'otherCostPrice',
      dataIndex: 'otherCostPrice',
      width: priceWidth[2],
      render: (_, record) => {
        const brandItem = record.prices.filter(item => item.brandId === defaultBrand)
        return amountRender(brandItem[0] && brandItem[0] && brandItem[0].otherCostPrice)
      }
    }, {
      title: '市场价',
      key: 'marketPrice',
      dataIndex: 'marketPrice',
      width: priceWidth[3],
      render: (_, record) => {
        const brandItem = record.prices.filter(item => item.brandId === defaultBrand)
        return amountRender(brandItem[0] && brandItem[0] && brandItem[0].marketPrice, 'money-red')
      }
    }, {
      title: '状态',
      key: 'activated',
      dataIndex: 'activated',
      width: 100,
      filters: [
        {text: "上架中", value: true},
        {text: "已下架", value: false}
      ],
      render: (text) => text ? <Tag color="#4CAF50" className="large">上架中</Tag> :
        <Tag className="large" color="#f50">已下架</Tag>
    }, {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <>
          <a onClick={() => updateProduct(record.id)}>编辑</a>
          <Divider type="vertical"/>
          <Popconfirm
            title={`确定要${record.activated ? "下架" : "上架"}此项目吗?`}
            placement="rightBottom"
            onConfirm={() => enableProduct(record)}
          >
            <a>{record.activated ? "下架" : "上架"}</a>
          </Popconfirm>
          <Divider type="vertical"/>
          <Popconfirm
            title="确定要删除此项目吗?"
            placement="rightBottom"
            onConfirm={() => onDelete(record.id)}
          >
            <a>删除</a>
          </Popconfirm>
        </>
      )
    }
  ]

  const [loading, setLoading] = useState(false);

  const onFileChange = ({file}) => {
    const {response} = file;
    setLoading(true);
    if (!response) {
      setLoading(true);
      return;
    }
    if (response.data.failedList && response.data.failedList[0] && response.data.failedList[0].message) {
      message.error(response.data.failedList[0].message)
      setLoading(false)
      return;
    }
    message.success("导入成功")
    setLoading(false);
    refresh().finally()
  }

  // const [importStyle, setImportStyle] = useState("append");

  const btnPrpos = {
    type: 'primary',
    disabled: items.length < 1,
    ghost: true,
    style: {marginLeft: 10}
  }

  const expandedRowRender = (record) => {
    const cols = [
      {
        title: '',
        key: 'placeholder2',
      },
      {
        title: '品牌',
        key: 'brandName',
        dataIndex: 'brandName',
        width: priceWidth[4],
        render: (v, r) => <Tag color={brandColors[r.brandId]}>{v}</Tag>
      },
      {
        title: '固定成本价',
        key: 'fixedCostPrice',
        dataIndex: 'fixedCostPrice',
        width: priceWidth[0],
        render: amountRender
      }, {
        title: '可变成本价',
        key: 'volatileCostPrice',
        dataIndex: 'volatileCostPrice',
        width: priceWidth[1],
        render: amountRender
      }, {
        title: '其他成本价',
        key: 'otherCostPrice',
        dataIndex: 'otherCostPrice',
        width: priceWidth[2],
        render: amountRender
      }, {
        title: '市场价',
        key: 'marketPrice',
        dataIndex: 'marketPrice',
        width: priceWidth[3],
        render: amountRender
      },
      {
        title: '',
        key: 'placeholder2',
        width: 280
      },
    ];
    return <Table rowKey={record => record.brandId} columns={cols} dataSource={record.prices || []} pagination={false}/>
  }

  const handleSelect = (value) => {
    setDefaultBrand(value);
  }

  return (
    <div className={'zr-panel'}>
      <div className={'zr-panel-header'}>
        <PageHeader backIcon={<ArrowLeftOutlined/>} onBack={() => window.history.back()} title='项目管理' subTitle=''/>
      </div>
      <div className={'zr-list-page-box body-bg body-border absolute'}>
        <div className={cs("zr-query-box")} style={{paddingRight: 20,}}>
          <div style={{fontSize: 14, marginRight: 8}}>价格显示</div>
          <Select placeholder="品牌" defaultValue={1} onChange={handleSelect} style={{minWidth: 100}}>
            {
              brandList && brandList.length > 0 && brandList.map(item => <Option key={item.id} value={item.id}>
                {item.name}
              </Option>)
            }
          </Select>
          <div style={{flexGrow: 1}}></div>
          <SearchAutoComplete style={{marginRight: 5}} allowClear={true} onSelect={onSearch} placeholder="请输入关键字查询"/>
          <Button style={{margin: "0 10px"}} type="primary"
                  onClick={() => props.history.push("/app/product/addcopy")}><PlusOutlined/>添加项目</Button>
          <Upload
            accept=".xls,.xlsx"
            name="file"
            action={`${HOST}/management/product/import/overwrite`}
            multiple={false}
            withCredentials={true}
            showUploadList={false}
            onChange={onFileChange}
          >
            <Button type={'primary'} danger>{loading ? <LoadingOutlined/> : <UploadOutlined/>} 从文件导入 </Button>
          </Upload>
          <Button type={'primary'}
                  onClick={() => downloadSync(`${HOST}/management/product/export`, "项目.xls")}
                  style={{marginLeft: 10}}>
            <VerticalAlignBottomOutlined/> 导出项目
          </Button>
          <Button
            {...btnPrpos}
            onClick={() => showConfirm("Enabled")}
          >
            批量上架
          </Button>
          <Button
            {...btnPrpos}
            onClick={() => showConfirm("Disabled")}
          >
            批量下架
          </Button>
          <Button
            {...btnPrpos}
            ghost={false}
            danger
            onClick={() => showConfirm("Delete")}
          >
            批量删除
          </Button>

        </div>
        <div className="zr-table-box">
          <Table
            {...tableProps}
            pagination={{
              ...pagination,
              ...pageSetting
            }}
            rowSelection={rowSelection}
            rowKey={record => record.id}
            size='middle'
            expandable={{expandedRowRender}}
            columns={productColumns}/>
        </div>
      </div>
    </div>
  )
}

export default Product;
